package com.tarena.platform.email;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * email配置帮助类
 * 
 * @author tarena
 *
 */
public class EmailConfig {
	private static Logger log = LoggerFactory.getLogger(PropertiesReader.class);
	// 配置参数类
	private static Map<String, String> proMap = new HashMap<>();
	private static Session mailSession;
	private static Transport transport;
	
	public static String apiUser = null;
	public static String apiKey = null;
	static {
		try {
			// 配置javamail
			Properties props = System.getProperties();
			props.setProperty("mail.transport.protocol", getValue("mail.transport.protocol"));
			props.put("mail.smtp.host", getValue("mail.smtp.host"));
			props.put("mail.smtp.port", getValue("mail.smtp.port"));
			props.setProperty("mail.smtp.auth", getValue("mail.smtp.auth"));
			props.put("mail.smtp.connectiontimeout", getValue("mail.smtp.connectiontimeout")); // 单位：毫秒
			props.put("mail.smtp.timeout", getValue("mail.smtp.timeout")); // 单位：毫秒
			props.setProperty("mail.mime.encodefilename", getValue("mail.mime.encodefilename"));
			// 使用api_user和api_key进行验证
			apiUser = getValue("email.user");// "zhanlong1988@126.com";
			apiKey = getValue("email.password");// "wangyi147";
			//没有配置用户名，密码就不进行实例
			if(StringUtils.isNotBlank(apiUser)&&StringUtils.isNotBlank(apiKey)) {
				mailSession = Session.getInstance(props, new Authenticator() {
					@Override
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(apiUser, apiKey);
					}
				});
			}
		} catch (Exception e) {
			log.error("init email service error.", e);
		}
	}
	
	public static Session getMailSession() throws Exception {
		if(null==mailSession) {
			throw new Exception("系统没有配置默认用户名，密码无法进行初始化");
		}
		return mailSession;
	}

	public static Transport getTransportInstance() throws Exception {
		if(null==transport) {
			transport = getMailSession().getTransport();
		}
		if(null==transport) {
			throw new Exception("获取发送器异常");
		}
		return transport;
	}

	/** 获取配置参数 **/
	public static String getValue(String key) {
		if (proMap == null || proMap.isEmpty()) {
			proMap = PropertiesReader.cacheProperties("platform_email.properties");
		}
		if (key == null || key.isEmpty()) {
			return null;
		}
		return proMap.get(key);
	}
}
